package com.zhuoyue.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhuoyue.biz.core.api.dao.TblPasswordShareMapper;
import com.zhuoyue.biz.core.api.domain.TblPasswordShare;
import com.zhuoyue.biz.core.api.service.impl.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * @author hewenze
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private TblPasswordShareMapper tblPasswordShareMapper;

    @Autowired
    private DeviceService deviceService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对redis数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // message.toString()可以获取失效的key
        String expiredKey = message.toString();
        String lockTimePsd ="com.zyzn.fingerprint.lock.time.psd" + "." ;
        if (expiredKey.startsWith(lockTimePsd)){
            System.out.println("进入了删除密码代码块");
            String deviceMac = getEndStr(expiredKey);
            QueryWrapper<TblPasswordShare> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("device_mac",deviceMac);
            queryWrapper.eq("type","many_times");
            int delete = tblPasswordShareMapper.delete(queryWrapper);
            if (delete>0){
                System.out.println("密码记录删除成功");
            }else {
                System.out.println("此密码不存在或已被删除");
            }
        }

    }
    public String getEndStr(String str) {
        int index = str.lastIndexOf(".");
        String extStr = str.substring(index+1);
        return extStr;
    }
}
